import SOE
----------------------------
-- Part 2 --

main :: IO ()
main = runGraphics (
         do w1 <- openWindow "HW1_2" (1200,600)
            sierpinskiRec w1 300 300 256
            sierpinskiCircle w1 900 300 256 White
            spaceClose w1
       )

spaceClose :: Window -> IO ()
spaceClose w = do k <- getKey w
                  if k == ' ' then closeWindow w
                              else spaceClose w
-- Part 2.1 --

minSize1 :: Int
minSize1 = 2

fillRec :: Window -> Int -> Int -> Int -> IO ()
fillRec w x y size = drawInWindow w (withColor Blue 
                    (polygon [(x,y), (x+size,y), (x+size, y-size), (x,y-size)]))

sierpinskiRec :: Window -> Int -> Int -> Int -> IO ()
sierpinskiRec w x y size 
               = if size <= minSize1
                 then fillRec w x y size 
                 else let size2 = size `div` 3
                          y2 = y  - size2
                          y3 = y2 - size2
                          x2 = x  + size2
                          x3 = x2 + size2
                   in do sierpinskiRec w x  y  size2
                         sierpinskiRec w x  y2 size2
                         sierpinskiRec w x  y3 size2
                         sierpinskiRec w x2 y  size2
                         sierpinskiRec w x2 y3 size2
                         sierpinskiRec w x3 y  size2
                         sierpinskiRec w x3 y2 size2
                         sierpinskiRec w x3 y3 size2

-- Part 2.2 --
minSize2 = 8

fillCircle w x y r color = drawInWindow w (withColor color 
                     (ellipse (x-r,y-r) (x+r,y+r)))

sierpinskiCircle w x y r c
                = if r <= minSize2
                  then fillCircle w x y r c
                  else 
                    let r2 = r `div` 2
                        c2 = if (c == White) then Blue else White 
                    in do fillCircle w x y r c
                          sierpinskiCircle w (x+r2) y r2 c2
                          sierpinskiCircle w (x-r2) y r2 c2
                          sierpinskiCircle w x (y+r2) r2 c2
                          sierpinskiCircle w x (y-r2) r2 c2
